package com.qingyun.framework.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.qingyun.framework.config.properties.WxMaProperties;
import com.qingyun.framework.config.properties.WxPayPropererties;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Classname WxConfig
 * @Author dyh
 * @Date 2021/9/16 15:55
 */
@Configuration
@AllArgsConstructor
@EnableConfigurationProperties({WxMaProperties.class,WxPayPropererties.class})
public class WxConfig {

	public WxMaProperties wxMaProperties;

	public WxPayPropererties wxPayPropererties;

	/**
	 * 用户小程序
	 * @return
	 */
	@Bean
	@ConditionalOnProperty(prefix = "wx", name = "enabled", havingValue = "true")
	public WxMaService getWxMaService() {
		WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
		config.setAppid(wxMaProperties.getAppid());
		config.setSecret(wxMaProperties.getSecret());
		config.setToken(wxMaProperties.getToken());
		config.setAesKey(wxMaProperties.getAesKey());
		config.setMsgDataFormat(wxMaProperties.getMsgDataFormat());
		WxMaService service = new WxMaServiceImpl();
		service.setWxMaConfig(config);
		return service;
	}

	@Bean
	@ConditionalOnProperty(prefix = "wx", name = "enabled", havingValue = "true")
	public WxPayService getWxPayService() {
	    WxPayConfig payConfig = new WxPayConfig();
		payConfig.setAppId(wxPayPropererties.getAppId());
		payConfig.setMchId(wxPayPropererties.getMchId());
		payConfig.setMchKey(wxPayPropererties.getMchKey());
		payConfig.setKeyPath(wxPayPropererties.getKeyPath());
		payConfig.setPrivateKeyPath(wxPayPropererties.getPrivateKeyPath());
		payConfig.setPrivateCertPath(wxPayPropererties.getPrivateCertPath());
		payConfig.setApiV3Key(wxPayPropererties.getApiV3Key());
		payConfig.setSignType(WxPayConstants.SignType.MD5);

		WxPayService wxPayService = new WxPayServiceImpl();

//      打开下面的代码，开启沙箱模式
//        if (Objects.equals(profile, "dev")) {
//            String sandboxSignKey = null;
//            try {
//                wxPayService.setConfig(payConfig);
//                sandboxSignKey = wxPayService.getSandboxSignKey();
//            } catch (WxPayException e) {
//                e.printStackTrace();
//            }
//            payConfig.setUseSandboxEnv(true);
//            payConfig.setMchKey(sandboxSignKey);
// }

		wxPayService.setConfig(payConfig);
		return wxPayService;
	}


}
